#include <iostream>
using namespace std;
#include <string>
#include <cerrno>
#include <unistd.h>
#include <cstring>
// 这四个头文件是写套接字经常用到的
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void Usage(string proc)
{
    cout << "Usage: " << proc << " server_ip server_port " << endl;
}

// ./udp_client server_ip server_port

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }
    // 1.创建套接字，TCP 使用SOCK_STREAM
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "socket error :" << errno << endl;
        return 1;
    }
    // 无需bind
    // 2. 建立连接
    // 链接服务器信息
    uint16_t srv_port = atoi(argv[2]);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(srv_port);
    server.sin_addr.s_addr = inet_addr(argv[1]);
    if (connect(sock, (sockaddr *)&server, sizeof(server)) < 0)
    {
        cout << "connect error " << endl;
        return 2;
    }
    // 连接成功
    cout << "connect success!" << endl;
    // 使用服务
    while (true)
    {
        cout << "发送消息:>";
        char buffer[1024] = {0};
        // 产生数据
        fgets(buffer, sizeof(buffer), stdin);
        // 往sock写入数据即可发送
        write(sock, buffer, strlen(buffer));
        // 读取服务器返回数据
        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        buffer[s] = 0;
        cout << "server return :>" << buffer << endl;
    }
    return 0;
}